package logic

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"user/public"

	"user/internal/svc"
	"user/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLaunchLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLaunchLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLaunchLogic {
	return &UserLaunchLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 退出登录
func (l *UserLaunchLogic) UserLaunch(in *user.UserLaunchRequest) (*user.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line
	//验参
	if in.Mobile == "" {
		return nil, status.Error(codes.InvalidArgument, "userMobile cannot be empty")
	}
	//用户是否存在  和   用户是否已经登录
	info := public.User{}
	err := public.DB.Table("user").Where("user_mobile =? AND user_login_status=?", in.Mobile, 1).First(&info).Error
	if err != nil {
		return nil, status.Error(codes.InvalidArgument, "mobile error user not find or User not logged in"+err.Error())
	}
	//修改用户登录状态
	ok, err := public.UpdateUserLoginStatus(info.UserID, 0)
	if err != nil {
		return nil, status.Error(codes.InvalidArgument, "update user_login_status error"+err.Error())
	}

	if !ok {
		return nil, status.Error(codes.InvalidArgument, "update user_login_status error")
	}

	return &user.UserRegisterResponse{
		Data: &user.UserInfo{
			UserId:     info.UserID,
			UserName:   info.UserName,
			UserMobile: info.UserMobile,
		},
	}, nil
}
